package com.zyl.blog.common.strategy;

import com.zyl.blog.common.annotation.Sensitive;

/**
 * 脱敏策略抽象基类
 * 提供通用的脱敏实现
 * @version v1.0
 * @ProjectName: Personal_Blog_Server
 * @Package: com.zyl.blog.common.strategy
 * @ClassName: AbstractSensitiveStrategy
 * @Author FinalFantasy
 * @Date 2025/9/8-10:29
 */
public abstract class AbstractSensitiveStrategy implements SensitiveStrategy {

    /**
     * 通用脱敏方法
     * 根据前缀长度和后缀长度保留字符，中间用maskChar填充
     */
    protected String mask(String value, int prefixLen, int suffixLen, char maskChar) {
        if (value == null || value.isEmpty()) {
            return value;
        }

        int len = value.length();

        // 计算需要保留的前缀和后缀
        int actualPrefixLen = Math.max(0, Math.min(prefixLen, len));
        int actualSuffixLen = Math.max(0, Math.min(suffixLen, len - actualPrefixLen));

        // 如果前缀+后缀超过总长度，直接返回原字符串
        if (actualPrefixLen + actualSuffixLen >= len) {
            return value;
        }

        // 构建脱敏字符串

        int maskLen = len - actualPrefixLen - actualSuffixLen;

        return value.substring(0, actualPrefixLen) +
                String.valueOf(maskChar).repeat(Math.max(0, maskLen)) +
                value.substring(len - actualSuffixLen);
    }

    @Override
    public String desensitize(String value, Sensitive annotation) {
        return mask(value, annotation.prefixLen(), annotation.suffixLen(), annotation.maskChar());
    }
}